package com.jinju.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.jinju.constant.JwtClaimsConstant;
import com.jinju.constant.MessageConstant;
import com.jinju.context.BaseContext;
import com.jinju.properties.JwtProperties;
import com.jinju.result.Result;
import com.jinju.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String url = request.getRequestURL().toString();
        log.info("请求的url：{}",url);
        if (url.contains("login") || url.contains("register")){
            log.info("登录操作，放行");
            return true;
        }
        String jwt = request.getHeader(jwtProperties.getPeopleTokenName());
        if (!StringUtils.hasLength(jwt)){
             log.info("请求头为空，返回未登录操作");
            Result error=Result.error(MessageConstant.NOT_LOGIN);
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJWT(jwtProperties.getPeopleSecretKey(), jwt);
            Long bId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            BaseContext.setCurrentId(bId);
            log.info("令牌合法，放行");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录信息");
            Result error=Result.error(MessageConstant.NOT_LOGIN);
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
